﻿//======================================================================
//
//        Copyright (C) 2015   
//        All rights reserved
//
//        filename : PutOutSendCard
//        description : 半成品/成品卡发放

//        created by XXX at  20150821
//
//======================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CardLogistics.Web.Components;
using CardLogistics.Model.CardMaking;
using System.Data;
using System.Text;
using CardLogistics.DAL.PutOutCard;

namespace CardLogistics.Web.MainPage.PutOutCard.PutOutSendCard
{
    public partial class AddEdit : BasePage
    {
        private static readonly CardLogistics.DAL.PutOutCard.PutOutSendCardData DAL = new DAL.PutOutCard.PutOutSendCardData();
        private static readonly CardLogistics.DAL.PutOutCard.PutOutSendCard_DetailData DDAL = new CardLogistics.DAL.PutOutCard.PutOutSendCard_DetailData();
        string SendCardId = "";//卡片发放Id
        protected Dictionary<string, string> CardTypeList = null;
        /// <summary>
        /// 盒号集合
        /// </summary>
        protected Dictionary<string, string> CardNOList = null;
        private static DataTable DtBox;//存放盒号等信息
        public static string TitleName;
        /// <summary>
        /// 箱号号集合
        /// </summary>
        protected string BoxNOList = "";

        protected Dictionary<string, string> CardNOList_D = null;

        #region 初始化
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            CardNOList = new Dictionary<string, string>();
            CardNOList_D = new Dictionary<string, string>();
            BoxNOList = "";
            if (!IsPostBack)
            {
                LEADINGDATE.Value = DateTime.Now.ToString("yyyy-MM-dd");//领用日期
                LEADINGPERSON.Value = LoggedUser.USERFULLNAME;//领用人默认为当前登录用户
                BindGroup();//绑定机构/网点树列表
                InitControl(sender, e);
            }
        }
        #endregion

        #region 绑定机构/网点树列表
        /// <summary>
        /// 绑定根节点
        /// </summary>
        void BindGroup()
        {
            DataTable dt = new DAL.Basic.Basic_SalesInfoData().GetList(" ISDELETE=0 ", "*");//获取所有节点
            if (dt != null && dt.Rows.Count > 0)
            {
                LEADINGUNIT.DataSource = dt;
                LEADINGUNIT.DataTextField = "SALESNAME";
                LEADINGUNIT.DataValueField = "Id";
                LEADINGUNIT.DataBind();
            }
        }
        #endregion

        #region 编辑时绑定值
        /// <summary>
        /// 编辑时绑定值
        /// </summary>
        public void InitControl(object sender, EventArgs e)
        {
            TitleName = GetStatusInfo(0, "半成品/成品卡发放");
            if (IsEdit)
            {
                string _key = Request.QueryString["id"];
                if (!string.IsNullOrEmpty(_key))
                {
                    CardLogistics.Model.PutOutCard.PutOutSendCard pData = DAL.GetModel(_key);
                    SetWebControls(this.Page, pData);
                    LEADINGUNIT.SelectedValue = pData.LEADINGUNIT; //销售机构/网点
                    hf_PutOutCardId.Value = pData.PUTOUTCARDID; //出库单号外键Id
                    DataTable dt = DDAL.GetInfoBySendcardId(pData.ID);
                    //dt.DefaultView.Sort = "StartCardNo ASC,EndNo ASC";
                    DataView dv = dt.DefaultView;
                    dv.Sort = "StartCardNo ASC,EndCardNo ASC";
                    dt = dv.ToTable();
                    string detId = "";
                    int editCardNum = 0;
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            detId += dr["cardno"].ToString() + "|" + dr["FlagName"].ToString() + "|" + dr["Fgvamt"].ToString() + "|" + dr["PreCharge"].ToString() + "|" + dr["StartCardNo"].ToString() + "|" + dr["EndCardNo"].ToString() + "|" +
                                     dr["duenumber"].ToString() + "|" + dr["actualnumber"].ToString() + "|" + dr["missingcardno"].ToString() + ";";

                            //获取编辑前的卡片数量
                            editCardNum += (Convert.ToInt32(dr["EndCardNo"].ToString()) - Convert.ToInt32(dr["StartCardNo"].ToString()) + 1);
                        }
                        hf_detailId.Value = detId.TrimEnd(';');
                        hf_EditSumCard.Value = editCardNum.ToString(); //获取编辑前的卡片数量
                    }
                    btn_Add.Visible = btn_Submit.Visible = false;

                    if (pData.ISSUBMIT == 0 || pData.ISSUBMIT == 3)//状态为 0(未提交) 或 3(驳回)时才可以进行编辑操作
                    {
                        btn_Add.Visible = btn_Submit.Visible = true;
                    }
                    TitleName = GetStatusInfo(int.Parse(pData.ISSUBMIT.ToString()), "半成品/成品卡发放");
                    //通过出库单ID得到出库总数量和已发放的总数量
                    DataTable putOutdt = CardLogistics.DAL.CommonData.GetList("*", "v_putoutcard", "ID='" + pData.PUTOUTCARDID + "'");
                    if (putOutdt.Rows.Count > 0)
                    {
                        hf_PutOutedTotal.Value = putOutdt.Rows[0]["PutOutedTotal"].ToString(); //出库总数量
                        hf_SendedTotal.Value = putOutdt.Rows[0]["SendedTotal"].ToString();//已发放数量

                        btn_PutOutId_ValueChanged(sender, e);
                    }
                }
            }
            else
            {
                hf_EditSumCard.Value = "0";
                SENDNO.Value = GetBillNumber("半成品/成品卡发放");
            }
        }
        #endregion

        #region 保存事件
        /// <summary>
        /// 保存按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Add_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(0);
                ShowMegByResult(result, 0);
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }
        #endregion

        #region 保存并提交事件
        /// <summary>
        /// 保存并提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(1);
                ShowMegByResult(result, 1);
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }
        #endregion

        #region 提示信息
        /// <summary>
        /// 提示信息
        /// </summary>
        /// <param name="result"></param>
        private void ShowMegByResult(string result, int issubmit)
        {
            if (result.Split(',')[0] == "ok")
            {
                if (issubmit == 1)
                {
                    InsertAppInfo(9, result.Split(',')[1]);// 9半成品/成品卡发放
                    InsertLog("保存并提交半成品/成品卡发放信息,单据单号:" + SENDNO.Value);
                }
                else
                    InsertLog("保存半成品/成品卡发放信息,单据编号:" + SENDNO.Value);
                ReturnListInfo();
            }
            else
            {
                ShowMessageBox("操作失败请重新操作！" + result.Split(',')[1]);
            }
        }
        #endregion

        #region 半成品/成品卡发放信息
        /// <summary>
        /// 半成品/成品卡发放信息
        /// </summary>
        /// <param name="issubmit">是否提交</param>
        /// <returns></returns>
        private string EncapsulationModel(int issubmit)
        {
            string result = string.Empty;
            CardLogistics.Model.PutOutCard.PutOutSendCard model = new Model.PutOutCard.PutOutSendCard();
            model = GetWebControls<CardLogistics.Model.PutOutCard.PutOutSendCard>(this.Page);
            model.LASTUPDATEUSER = LoggedUser.ID;
            model.LASTUPDATEDATE = DateTime.Now;
            model.ADDTIME = DateTime.Now;
            model.ISDELETE = 0;
            model.ISSUBMIT = issubmit;
            model.PUTOUTCARDID = hf_PutOutCardId.Value; //半成品/成品卡出库单号ID
            SendCardId = model.ID;//获取卡片发放单ID
            model.LEADINGUNIT = LEADINGUNIT.SelectedValue; //销售机构/网点
            string FileValue = hf_detailId.Value; //半成品/成品卡出库明细字段
            if (IsEdit)
            {
                model.ID = Request.QueryString["id"];
                result = DAL.Update(model, FileValue);
            }
            else
            {
                result = DAL.Add(model, FileValue);
                if (result.Split(',')[0] == "ok")
                {
                    ChgBillNumber("半成品/成品卡发放");
                }
            }
            return result;
        }
        #endregion

        #region 通过半成品/成品出库单ID获取详细信息
        /// <summary>
        /// 通过半成品/成品出库单ID获取详细信息事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_PutOutId_ValueChanged(object sender, EventArgs e)
        {
            if (hf_PutOutCardId.Value !="")
            {
                string id = "";
                if (IsEdit)
                    id = Request.QueryString["id"].ToString();
                DtBox = DAL.GetBoxInfo(hf_PutOutCardId.Value, id);//获取盒号、卡类型等信息
                //当审核不通过(IsSubmit=4)时获取半成品/成品发放盒号等信息
                if (DtBox.Rows.Count == 0)
                    DtBox = CardLogistics.DAL.CommonData.GetList("*", "v_putoutsendcard_detail", "SendCardId='" + id + "' and IsSubmit=4");
                //DtBox.DefaultView.Sort = "CardNo ASC";//按盒号排序
                DataView dv = DtBox.DefaultView;
                dv.Sort = "CardNo ASC";//按盒号排序
                DtBox = dv.ToTable();
                rkId.Value = DtBox.Rows[0]["CheckId"].ToString();//获取入库Id
                zkId.Value = DtBox.Rows[0]["zkId"].ToString();//获取制卡入库Id
                CardNOList = new Dictionary<string, string>();
                CardNOList_D = new Dictionary<string, string>();
                BoxNOList = "";
                foreach (DataRow d in DtBox.Rows)
                {
                    if (!CardNOList.Values.Contains(d["cardno"].ToString().Trim()))
                    {
                        //是否启用|卡押金|预充值|开始卡号|结束卡号
                        CardNOList.Add(d["FlagName"].ToString() + "|" + d["Fgvamt"].ToString() + "|" + d["PreCharge"].ToString() + "|" + d["StartCardNo"].ToString() + "|" + d["EndCardNo"].ToString() + "|" + d["CheckId"].ToString() + "|" + d["zkId"].ToString(), d["CardNo"].ToString().Trim());
                    }
                    if (!BoxNOList.Split(',').Contains(d["boxno"].ToString()))
                    {
                        BoxNOList += d["boxno"].ToString() + ",";
                        CardNOList_D.Add(GetCardNOListByBox(d["boxno"].ToString(), dv), d["boxno"].ToString());
                    }
                }
                BoxNOList = "'" + BoxNOList.TrimEnd(',') + "'";
            }
        }
        /// <summary>
        /// 根据箱号获取盒号，并用“|”拼接
        /// </summary>
        /// <param name="box"></param>
        /// <param name="dvAll"></param>
        /// <returns></returns>
        private string GetCardNOListByBox(string box, DataView dvAll)
        {
            string cardNoStr = "";
            for (int i = 0; i < dvAll.Count; i++)
            {
                if (dvAll[i]["boxno"].ToString() == box)
                    cardNoStr += dvAll[i]["cardno"].ToString() + "|";
            }
            return cardNoStr.TrimEnd('|');
        }
        #endregion
    }
}